import { Command } from '../constant';
import Taro from '@tarojs/taro';
import { Dispatch } from 'typings';
import { IAllReducerProps } from '../types';
import { getReducerData } from '@/redux/store';
import { extraPathsValue } from '@/redux/util';
import api from 'api';

export default (dispatch: Dispatch) => {
  let action = {
    commonChange(...param: any) {
      dispatch({
        type: Command.commonChange,
        payload: extraPathsValue(...arguments),
      });
    },
    async page() {
      this.getAppCity()
      this.getHouseUser();
    },
    /**
    * 添加房屋回填业主信息
    */
    async getHouseUser() {
      let userInfo = (Taro.getStorageSync('b2b-wechat@login')).user;
      let selectDistance = Taro.getStorageSync('selectDistance');
      let params = {
        phone: userInfo.phone,
        communityId: selectDistance.id,
      };
      let res = await api.houseController.findHouseByUserId(params);
      if (res.code == '200') {
        let userName = '';
        if (userInfo.phone == res.data.ownerPhone) {
          userName = res.data.ownerName;
        } else if (userInfo.phone == res.data.alternateOwnerPhone) {
          userName = res.data.alternateOwnerName;
        }
        action.commonChange([
          { paths: 'main.House', value: res.data },
          { paths: 'main.phone', value: userInfo.phone },
          { paths: 'main.userName', value: userName },
          { paths: 'main.houseHoldType', value: userName ? '1' : '' },
          { paths: 'main.checked', value: userName ? '1' : '' },
        ]);
      }
    },
    /**
    * 查询城市列表
    */
    async getAppCity() {
      let res = await api.houseController.findAllCity();
      if (res.code == '200') {
        if (res.data.length > 0) {
          let arr = [], city = '';
          res.data.map(e => {
            arr.push(e.city);
          });
          city = arr[0]
          action.commonChange([
            { paths: 'main.areas', value: arr },
            { paths: 'main.city', value: city },
          ]);
          this.getAppCommunity(city);
        }
      } else {
        Taro.showToast({
          title: res.msg,
          icon: 'none',
          duration: 2000,
        });
      }
    },
    /**
    * 查询小区列表
    */
    async getAppCommunity(city) {
      let res = await api.houseController.findCommunityByCity({ city });
      let selectDistance = Taro.getStorageSync('selectDistance');
      if (res.code == '200') {
        if (res.data.length > 0) {
          let arr = [];
          res.data.map(e => {
            arr.push(e.name);
          });
          action.commonChange([
            { paths: 'main.xiaoquArrAll', value: res.data },
            { paths: 'main.xiaoquArr', value: arr },
            { paths: 'main.xiaoqu', value: selectDistance.name }
          ]);
          this.httpByBuilding(selectDistance.id);
        } else {
          Taro.showToast({
            title: '该区域没有小区',
            icon: 'none',
            duration: 2000,
          });
        }
      } else {
        Taro.showToast({
          title: res.msg,
          icon: 'none',
          duration: 2000,
        });
      }
    },
    /**
    * 查询楼栋列表
    */
    async httpByBuilding(communityId) {
      let { House } = getData().main;
      let res = await api.houseController.findByCommunityId({ communityId });
      if (res.code == '200') {
        if (res.data.length > 0) {
          let arr = [], buildingName = '';
          res.data.map(e => {
            arr.push(e.buildingName);
            if (House.buildingId == e.id) {
              buildingName = e.buildingName;
            }
          });
          action.commonChange([
            { paths: 'main.buildingListAll', value: res.data },
            { paths: 'main.buildingList', value: arr },
            { paths: 'main.buildingName', value: buildingName }
          ]);
          if (buildingName != '') {
            this.findByBuildingId(House.buildingId)
          }
        } else {
          Taro.showToast({
            title: '未查询到楼栋',
            icon: 'none',
            duration: 2000,
          });
        }
      } else {
        Taro.showToast({
          title: res.msg,
          icon: 'none',
          duration: 2000,
        });
      }
    },
    /**
    * 查询单元列表
    */
    async findByBuildingId(id) {
      let { House } = getData().main;
      let res = await api.houseController.findByBuildingId({ id });
      if (res.code == '200') {
        if (res.data.length > 0) {
          let arr = [], unitName = '';
          res.data.map(e => {
            arr.push(e.unitName);
            if (House.unitId == e.id) {
              unitName = e.unitName;
            }
          });
          action.commonChange([
            { paths: 'main.unitListAll', value: res.data },
            { paths: 'main.unitList', value: arr },
            { paths: 'main.unitName', value: unitName }
          ]);
          if (unitName != '') {
            this.findByUnitId(House.unitId)
          }
        } else {
          Taro.showToast({
            title: '该楼栋下还未添加单元',
            icon: 'none',
            duration: 2000,
          });
        }
      } else {
        Taro.showToast({
          title: res.msg,
          icon: 'none',
          duration: 2000,
        });
      }
    },
    /**
    * 查询房屋列表
    */
    async findByUnitId(unitId) {
      let { House } = getData().main;
      let res = await api.houseController.findByUnitId({ unitId });
      if (res.code == '200') {
        if (res.data.length > 0) {
          let arr = [], houseName = '';
          res.data.map(e => {
            arr.push(e.houseCode);
            if (House.id == e.id) {
              houseName = e.houseCode;
            }
          });
          action.commonChange([
            { paths: 'main.houseListAll', value: res.data },
            { paths: 'main.houseList', value: arr },
            { paths: 'main.houseId', value: House.id },
            { paths: 'main.houseName', value: houseName },
          ]);
        } else {
          Taro.showToast({
            title: '该单元下还未添加房屋',
            icon: 'none',
            duration: 2000,
          });
        }
      } else {
        Taro.showToast({
          title: res.msg,
          icon: 'none',
          duration: 2000,
        });
      }
    },
    /**
    * 清除数据
    */
    async clearValue(type) {
      if (type == 1) {
        action.commonChange('main.xiaoquArrAll', []);
        action.commonChange('main.xiaoquArr', []);
        action.commonChange('main.xiaoqu', '');
      }
      if (type == 1 || type == 2) {
        action.commonChange('main.buildingListAll', []);
        action.commonChange('main.buildingList', []);
        action.commonChange('main.buildingName', '');
      }
      if (type == 1 || type == 2 || type == 3) {
        action.commonChange('main.unitListAll', []);
        action.commonChange('main.unitList', []);
        action.commonChange('main.unitName', '');
      }
      if (type == 1 || type == 2 || type == 3 || type == 4) {
        action.commonChange('main.houseListAll', []);
        action.commonChange('main.houseList', []);
        action.commonChange('main.houseName', '');
      }
    },
    /**
     * 发送验证码事件
     */
    async sendCode() {
      let { phone } = getData().main;
      if (phone == '') {
        Taro.showToast({
          title: '请输入手机号',
          icon: 'none',
          duration: 2000,
        });
        return false;
      }
      if (!/^1[3456789]\d{9}$/.test(phone)) {
        Taro.showToast({
          title: '请输入正确的手机号码',
          icon: 'none',
          duration: 2000,
        });
        return false;
      }
      try {
        await api.pagesIndexController.sendCode({ phone, vCodeType: 3 });
        Taro.showToast({
          title: '验证码发送成功',
          icon: 'none',
          duration: 2000,
        });
      } catch (error) {
        return false;
      }
      return true;
    },
    /**
    * 提交
    */
    async submitClick(houseHoldType) {
      let { houseId, userName, phone, vCode } = getData().main;
      if (houseHoldType == '') {
        Taro.showToast({
          title: '请选择身份',
          icon: 'none',
          duration: 2000,
        });
        return false;
      }
      if (houseId == '') {
        Taro.showToast({
          title: '请选择房屋',
          icon: 'none',
          duration: 2000,
        });
        return false;
      }
      if (userName == '') {
        Taro.showToast({
          title: '请输入姓名',
          icon: 'none',
          duration: 2000,
        });
        return false;
      }
      if (phone == '') {
        Taro.showToast({
          title: '请输入手机号',
          icon: 'none',
          duration: 2000,
        });
        return false;
      }
      if (!/^1[3456789]\d{9}$/.test(phone)) {
        Taro.showToast({
          title: '请输入正确的手机号码',
          icon: 'none',
          duration: 2000,
        });
        return false;
      }
      if (vCode == '') {
        Taro.showToast({
          title: '请输入验证码',
          icon: 'none',
          duration: 2000,
        });
        return false;
      }
      Taro.showLoading({
        title: '提交中...',
      })
      let userInfo = (Taro.getStorageSync('b2b-wechat@login')).user;
      let params = {
        houseHoldName: userName,
        houseHoldPhone: phone,
        vCode: vCode,
        userId: userInfo.id,
        houseHoldType: houseHoldType,
        houseId: houseId,
        appType: 1,
      }
      let res = await api.houseController.addUserHouse(params);
      Taro.hideLoading()
      if (res.success) {
        this.getDefHouseInfo(userInfo.id)
        Taro.showToast({
          title: '房屋绑定已完成，正在审核中',
          icon: 'none',
          duration: 2000,
        });
        Taro.navigateBack();
      } else {
        Taro.showToast({
          title: res.msg,
          icon: 'none',
          duration: 2000,
        });
      }
    },
    /**
     * 更新用户信息
     */
    async getDefHouseInfo(userId) {
      let userInfo = Taro.getStorageSync('b2b-wechat@login');
      const params = {
        userId
      };
      let res = await api.pagesIndexController.findDefHouseByUserId(params);
      if (res.success && res.data) {
        userInfo.user.communityCode = res.data.communityCode;
        userInfo.user.communityId = res.data.communityId;
        userInfo.user.communityName = res.data.communityName;
        userInfo.user.houseId = res.data.houseId;
        userInfo.user.status = res.data.status;
        Taro.setStorageSync('b2b-wechat@login', userInfo);
      } else {
        userInfo.user.communityCode = '';
        userInfo.user.communityId = '';
        userInfo.user.communityName = '';
        userInfo.user.houseId = '';
        userInfo.user.status = '';
        Taro.setStorageSync('b2b-wechat@login', userInfo);
      }
    },
  };
  return action;
};

function getData(): IAllReducerProps {
  return {
    main: getReducerData('packageAAddHouseMain'),
  };
}

//create by moon https://github.com/creasy2010/moon
